//用户行为分析常量
ubalogConstants = {
    url: '', //默认请求地址
    configJsonUrl: '',
    action: { //动作
        OPEN: 'OPEN',
        CLOSE: 'CLOSE',
        DLG: 'DLG',
        BUTTON: 'BUTTON' //按钮
    },
    BATCH_SENDER_NUMBER: 5, //定时发送的数量
    ENV_FIELDS: ['sip', 'os', 'rt', 'bro', 'osv', 'av', 'di', 'db', 'op'], //环境变量数据
    ubaEnable: true, //是否启用用户行为分析 默认为是,
    openTime: new Date().getTime(), //页面访问时间
    openTimeMap: {}, //组件页面义打开时间Map
    GETUBACONFIGMIDDLETIME: 600 //请求配置时间间隔 单位秒
};
(function() {
    //请求的url和启用控制从localstorage里获取，没有获取到再尝试下读取文件
    var YYTUBA = {};
    var Constants = Constants || {};
    YYTUBA.addEvent = function(object, name, func) {
        object.attachEvent ? object.attachEvent('on' + name, function(name) {
            func.call(object, name)
        }) : object.addEventListener && object.addEventListener(name, func, false)
    };
    YYTUBA.addEvent(window, 'load', function() {
        //1. 先从localstorage中获取
        var ubaURL = window.localStorage.UBAURL;
        var ubaEnable = window.localStorage.UBAENABLE == 'true' ? true : false;
        if (Constants.saveAccessBtnLog == 'true') {
            var ubaEnableLogBtn = true;
        } else {
            var ubaEnableLogBtn = window.localStorage.UBAENABLELOGBTN == 'true' ? true : false;
        }
        if (!ubaURL || !ubaEnable) {
            var chcpUrl = '';
            loadUbaConfig();
        } else {
            var lastGetUbaConfigTime = window.localStorage.lastGetUbaConfigTime || 0;
            var curTime = new Date().getTime();
            //如果 localStorage 已有配置信息,且超过缓存时间 需要从新请求,移动端或则超过时间的就要重新查询
            if ('uftportal' != YYTUbaLogUtils.getBrowserVersion() && ((curTime - lastGetUbaConfigTime) > ubalogConstants.GETUBACONFIGMIDDLETIME * 1000)) {
                loadUbaConfig();
            } else {
                ubalogConstants.url = ubaURL;
                ubalogConstants.ubaEnable = ubaEnable;
                ubalogConstants.ubaEnableLogBtn = ubaEnableLogBtn;
                if (ubalogConstants.ubaEnable) {
                    setTimeout(loadPage, 500);
                }
            }
        };

        function loadUbaConfig() {
            //纯h5界面走配置
            if (typeof(YC) != 'undefined' && YC && YC.StaticAppProps) {
                chcpUrl = YC.StaticAppProps.APP_ROOT_URL + YC.StaticAppProps.CHCP_URL;
            } else {
                if (Constants.isYytPlatform) {
                    chcpUrl = '/yyt-platform';
                }
                chcpUrl += "/webnc-resource-webapp/js/ubaconfig.txt"
            }
            if (chcpUrl) {
                //纯H5页面走远程配置
                // YYTUbaLogUtils.ajaxPost(chcpUrl, null, function (result) {
                //     //如果有请求到json文件就按json文件的配置
                //     var ubaConfig = JSON.parse(result);
                //     ubalogConstants.url = ubaConfig.ubaUrl;
                //     if(Constants.isYytPlatform){
                //         ubalogConstants.url = '/marketing-orderplatform/uba/ubalog';
                //     }
                //     ubalogConstants.ubaEnable = ubaConfig.ubaEnable;
                //     ubalogConstants.ubaEnableLogBtn = ubaConfig.ubaEnableLogBtn || false;
                //     //存到localStorage 里  UBAURL UBAENABLE
                //     window.localStorage.setItem('lastGetUbaConfigTime', new Date().getTime());
                //     window.localStorage.setItem('UBAURL', ubalogConstants.url);
                //     window.localStorage.setItem('UBAENABLE', ubaConfig.ubaEnable);
                //     window.localStorage.setItem('UBAENABLELOGBTN', ubaConfig.ubaEnableLogBtn);
                //     if (ubalogConstants.ubaEnable)//是否启用用户行为分析
                //         setTimeout(loadPage, 500);
                // },function(result){
                //    if(Constants.isYytPlatform){
                ubalogConstants.url = '/marketing-orderplatform/uba/ubalog';
                ubalogConstants.ubaEnable = true;
                ubalogConstants.ubaEnableLogBtn = true;
                //存到localStorage 里  UBAURL UBAENABLE
                window.localStorage.setItem('lastGetUbaConfigTime', new Date().getTime());
                window.localStorage.setItem('UBAURL', ubalogConstants.url);
                window.localStorage.setItem('UBAENABLE', ubalogConstants.ubaEnable);
                window.localStorage.setItem('UBAENABLELOGBTN', ubalogConstants.ubaEnableLogBtn);
                setTimeout(loadPage, 500);
                //     }
                // });
            }
        };
        /**
         * 记录用户行为
         */
        function setUbaLog(action, ubaData) {
            setTimeout(function() {
                if (typeof(YYTUbaLogUtils) == 'object') {
                    ubaData = ubaData || {};
                    ubaData.at = action;
                    YYTUbaLogUtils.logUba(ubaData);
                }
            }, 0);
        };
        //加载页面
        function loadPage() {
            try {
                // 浙江oa待办集成，需要将页面放在他们的框架中，会报accessing a cross-origin frame. add by chenbd
                if (window.top.isAlreadyUba && document.URL.indexOf('_card') == -1) {
                    YYTUbaLogUtils.logUba({
                        'at': ubalogConstants.action.BUTTON,
                        'btn': '查询'
                    });
                } else {
                    YYTUbaLogUtils.logUba({
                        'at': ubalogConstants.action.OPEN
                    });
                    window.top.isAlreadyUba = true;
                }
                //离开页面
                YYTUBA.addEvent(window, 'beforeunload', function(e) {
                    YYTUbaLogUtils.logUba({
                        'at': ubalogConstants.action.CLOSE
                    });
                });
            } catch (err) {

            }
        };
        //监听按钮点击事件
        $('button[type="button"]').click(function() {
            var text = $(this).text();
            if (text) {
                text = text.trim();
            }
            //打印按钮需要记录打印数量,已做特殊处理
            if ('打印' != text) {
                setUbaLog('BUTTON', {
                    btn: text
                });
            }
            //兼容ext的按钮下拉
            setTimeout(function() {
                var buttonItems = $('.x-menu-list-item');
                if (buttonItems && buttonItems.length > 0) {
                    $('.x-menu-list-item').one('click', function() {
                        var text = $(this).text();
                        if ('打印' != text) {
                            setUbaLog('BUTTON', {
                                btn: text
                            });
                        }
                    });
                }
            }, 500);

        });

    });
})();

YYTUbaLogUtils = {
    /**
     * _hmt.push(['_trackEvent', category, action, opt_label, opt_value]);
     category：要监控的目标的类型名称，通常是同一组目标的名字，比如"视频"、"音乐"、"软件"、"游戏"等等。该项必填，不填、填"-"的事件会被抛弃。
     action：用户跟目标交互的行为，如"播放"、"暂停"、"下载"等等。该项必填，不填、填"-"的事件会被抛弃。
     opt_label：事件的一些额外信息，通常可以是歌曲的名称、软件的名称、链接的名称等等。该项选填，不填、填"-"代表此项为空。
     opt_value：事件的一些数值信息，比如权重、时长、价格等等，在报表中可以看到其平均值等数据。该项可选。
     */
    //业务调这个,要指定动作,没有指定动作就不调用记录
    trackEvent: function(action) {
        if (!action)
            return;
        YYTUbaLogUtils.logUba({
            'at': action
        });
    },
    //记录弹窗页面，用户行为（vue写的页面只有show，hide，不会打开新的html，这个方法需要子啊show=OPEN、hide=CLOSE）
    logUbaByPopupPage: function(ubalogData) {
        // 记录打开时间
        if (ubalogData['at'] == ubalogConstants.action.OPEN) {
            ubalogConstants.openTimeMap[ubalogData['pt']] = new Date().getTime();
        }

        // 计算页面停留时间
        if (ubalogData['at'] == ubalogConstants.action.CLOSE) {
            var closeTime = new Date().getTime(); //离开时间
            var openTime = ubalogConstants.openTimeMap[ubalogData['pt']] || closeTime;
            delete ubalogConstants.openTimeMap[ubalogData['pt']];
            var st = closeTime - openTime;

            ubalogData['st'] = st;
        }

        YYTUbaLogUtils.logUba(ubalogData);
    },
    //记录用户行为
    logUba: function(ubalogData) {
        if (!ubalogData || !ubalogConstants.ubaEnable)
            return;
        //如果是关闭页面要统计staytime
        if (ubalogConstants.action.CLOSE == ubalogData['at'] && ubalogConstants.openTime && !ubalogData['st']) {
            var closeTime = new Date().getTime(); //离开时间
            ubalogData['st'] = closeTime - ubalogConstants.openTime;
        }
        var data = YYTUbaLogUtils.getPageInfo(ubalogData);
        // FIXME 订货平台全部采用实时记录 20230711 modify by linf
        // if(ubalogConstants.ubaEnableLogBtn && 'BUTTON' == ubalogData.at){
        //     //批量记录（满5条或隔天了，发一次）
        //     var uba = new YYTUbaLogUtils.LogUbaBatch();
        // }else{
        //实时记录
        var uba = new YYTUbaLogUtils.LogUbaRealTime();
        // }
        uba.logUba(data);
    },

    //------------------------批量模式-----------------------------------
    //批量记录用户行为分析
    LogUbaBatch: function() {

        this.logUba = function(ubalogData) {
            //1.记录用户行为
            this.recordUba(ubalogData);
            //2.发送用户行为
            this.sendUba();
        };
        //记录用户行为
        this.recordUba = function(ubalogData) {
            //初始化
            var storage = window.localStorage;
            //1.判断localStorage 中是否存在用户行为分析记录,有则取出来
            var ubalog = null;
            if (storage.ubalog) {
                ubalog = JSON.parse(storage.ubalog);
            }
            if (!ubalog) {
                ubalog = {
                    lastSendDate: '', //最后一次发送时间:初始化的时候不要初始化日期
                    isSend: false, // 是否发送
                    actionInfo: [], //动作数据
                    envInfo: null //环境变量数据
                };
            }
            //2.分离出动作数据和环境数据
            //2.1构造环境信息数据
            var envData = {};
            for (var key in ubalogConstants.ENV_FIELDS) {
                var field = ubalogConstants.ENV_FIELDS[key];
                if (ubalogData[field]) {
                    envData[field] = ubalogData[field];
                    delete ubalogData[field];
                }
            }
            ubalog.envInfo = envData;
            //2.2构造动作信息数据
            ubalogData['cts'] = YYTUbaLogUtils.getCurrentTs(); //时间戳
            ubalogData['cd'] = YYTUbaLogUtils.getCurrentDate(); //日期
            ubalogData['cy'] = YYTUbaLogUtils.getCurrentYear(); //年
            ubalogData['cm'] = YYTUbaLogUtils.getCurrentMonth(); //月
            ubalog.actionInfo.push(ubalogData);

            //3.判定是否需要发送数据：隔日期第一次就需要发送（缓存池里所有数据）2.满批量条数就要发送
            var currentDate = YYTUbaLogUtils.getCurrentDate();
            if (currentDate != ubalog.lastSendDate || ubalog.actionInfo.length >= ubalogConstants.BATCH_SENDER_NUMBER) {
                ubalog.isSend = true;
            } else {
                ubalog.isSend = false;
            }
            storage.setItem('ubalog', JSON.stringify(ubalog));
        };

        //发送用户行为
        this.sendUba = function() {
            var storage = window.localStorage;
            var ubalog = null;
            if (storage.ubalog) {
                ubalog = JSON.parse(storage.ubalog);
            }
            //有异常情况 没有ubalog
            if (!ubalog)
                return;
            //不需要发送
            if (!ubalog.isSend)
                return;
            //需要发送
            var data = 'bu=' + encodeURIComponent(JSON.stringify(ubalog));
            if (typeof(getCookie) == 'function') {
                var usercode = getCookie('usercode');
                if (usercode) {
                    data += '&usercode=' + usercode;
                }
            }

            YYTUbaLogUtils.ajaxPost(ubalogConstants.url, data);
            //清除记录数据
            ubalog = {
                lastSendDate: YYTUbaLogUtils.getCurrentDate(), //最后一次发送时间
                isSend: false, // 是否发送
                actionInfo: [], //动作数据
                envInfo: null //环境变量数据
            };
            storage.setItem('ubalog', JSON.stringify(ubalog));
        }
    },

    //-------------------------实时模式------------------------------------
    //实时记录用户行为分析
    LogUbaRealTime: function() {
        //记录用户行为分析
        this.logUba = function(ubalogData) {
            // TODO ：  在这儿发送的请求
            ubalogData['cts'] = YYTUbaLogUtils.getCurrentTs(); //时间戳
            ubalogData['cd'] = YYTUbaLogUtils.getCurrentDate(); //日期
            ubalogData['cy'] = YYTUbaLogUtils.getCurrentYear(); //年
            ubalogData['cm'] = YYTUbaLogUtils.getCurrentMonth(); //月

            var InfoStr = JSON.stringify(ubalogData);
            var data = 'u=' + encodeURIComponent(InfoStr);
            if (typeof(getCookie) == 'function') {
                var usercode = getCookie('usercode');
                if (usercode) {
                    data += '&usercode=' + usercode;
                }
            }

            YYTUbaLogUtils.ajaxPost(ubalogConstants.url, data);
        }
    },
    //--------------------工具类其他方法-----------------------------------
    //获取页面信息
    getPageInfo: function(ubalogData) {
        var pageinfo = {};
        pageinfo['sip'] = document.location.host; //服务器ip
        pageinfo['os'] = YYTUbaLogUtils.getCurrentSystem(); //操作系统
        pageinfo['rt'] = YYTUbaLogUtils.getResolution(); //分辨率
        pageinfo['bro'] = YYTUbaLogUtils.getBrowserVersion(); //浏览器
        /**此处开给业务的口子,业务自己定义用户行为分析的部分信息*/
        if (typeof(getYytBusiUbalogInfo) == 'function') {
            var busiPageInfo = getYytBusiUbalogInfo(ubalogData);
            for (var key in busiPageInfo)
                pageinfo[key] = busiPageInfo[key];
        }
        //调用时的参数比如 动作,页面停留时间
        if (ubalogData) {
            for (var key in ubalogData)
                pageinfo[key] = ubalogData[key];
        }
        return pageinfo;
    },
    //检测浏览器版本
    getBrowserVersion: function() {
        var agent = navigator.userAgent.toLowerCase();
        var arr = [];
        var Browser = "";
        var Bversion = "";
        var verinNum = "";
        //IE
        if (agent.indexOf("msie") > 0) {
            var regStr_ie = /msie [\d.]+;/gi;
            Browser = "IE";
            Bversion = "" + agent.match(regStr_ie)
        }
        //firefox
        else if (agent.indexOf("firefox") > 0) {
            var regStr_ff = /firefox\/[\d.]+/gi;
            Browser = "firefox";
            Bversion = "" + agent.match(regStr_ff);
        }
        //Chrome
        else if (agent.indexOf("chrome") > 0) {
            var regStr_chrome = /chrome\/[\d.]+/gi;
            Browser = "chrome";
            Bversion = "" + agent.match(regStr_chrome);
        }
        //Safari
        else if (agent.indexOf("safari") > 0 && agent.indexOf("chrome") < 0) {
            var regStr_saf = /version\/[\d.]+/gi;
            Browser = "safari";
            Bversion = "" + agent.match(regStr_saf);
        }
        //Opera
        else if (agent.indexOf("opera") >= 0) {
            var regStr_opera = /version\/[\d.]+/gi;
            Browser = "opera";
            Bversion = "" + agent.match(regStr_opera);
        }
        //移动H5
        else if (agent.indexOf("uftportal") >= 0) {
            Browser = "uftportal";
            verinNum = "";
        }
        //阿里客户端（生活号情况下）
        else if (agent.indexOf("alipayclient") >= 0) {
            Browser = "alipayclient";
            verinNum = "";
        } else {
            var browser = navigator.appName;
            if (browser == "Netscape") {
                var version = agent.split(";");
                var trim_Version = version[7].replace(/[ ]/g, "");
                var rvStr = trim_Version.match(/[\d\.]/g).toString();
                var rv = rvStr.replace(/[,]/g, "");
                Bversion = rv;
                Browser = "IE"
            }
        }
        verinNum = (Bversion + "").replace(/[^0-9.]/ig, "");
        arr.push(Browser);
        arr.push(verinNum);
        return Browser + verinNum;
    },
    //检测是否是XX浏览器
    WB: (function() {
        var UserAgent = navigator.userAgent.toLowerCase();
        return {
            isIE6: /msie 6.0/.test(UserAgent), // IE6
            isIE7: /msie 7.0/.test(UserAgent), // IE7
            isIE8: /msie 8.0/.test(UserAgent), // IE8
            isIE9: /msie 9.0/.test(UserAgent), // IE9
            isIE10: /msie 10.0/.test(UserAgent), // IE10
            isIE11: /msie 11.0/.test(UserAgent), // IE11
            isLB: /lbbrowser/.test(UserAgent), // 猎豹浏览器
            isUc: /ucweb/.test(UserAgent), // UC浏览器
            is360: /360se/.test(UserAgent), // 360浏览器
            isBaidu: /bidubrowser/.test(UserAgent), // 百度浏览器
            isSougou: /metasr/.test(UserAgent), // 搜狗浏览器
            isChrome: /chrome/.test(UserAgent.substr(-33, 6)), // Chrome浏览器
            isFirefox: /firefox/.test(UserAgent), // 火狐浏览器
            isOpera: /opera/.test(UserAgent), // Opera浏览器
            isSafire: /safari/.test(UserAgent) && !/chrome/.test(UserAgent), // safire浏览器
            isQQ: /qqbrowser/.test(UserAgent)
            //qq浏览器
        };
    })(),
    //检测当前的操作系统
    getCurrentSystem: function() {
        var sUserAgent = navigator.userAgent;
        var isAndroid = sUserAgent.indexOf('Android') > -1 ||
            sUserAgent.indexOf('Adr') > -1; //android终端
        var isiOS = !!sUserAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        if (isAndroid) {
            return "Android";
        } else if (isiOS) {
            return "IOS";
        }

        var isWin = (navigator.platform == "Win32") ||
            (navigator.platform == "Windows");
        var isMac = (navigator.platform == "Mac68K") ||
            (navigator.platform == "MacPPC") ||
            (navigator.platform == "Macintosh") ||
            (navigator.platform == "MacIntel");
        if (isMac)
            return "Mac";
        var isUnix = (navigator.platform == "X11") && !isWin && !isMac;
        if (isUnix)
            return "Unix";
        var isLinux = (String(navigator.platform).indexOf("Linux") > -1);
        if (isLinux)
            return "Linux";
        if (isWin) {
            var isWin2K = sUserAgent.indexOf("Windows NT 5.0") > -1 ||
                sUserAgent.indexOf("Windows 2000") > -1;
            if (isWin2K)
                return "Win2000";
            var isWinXP = sUserAgent.indexOf("Windows NT 5.1") > -1 ||
                sUserAgent.indexOf("Windows XP") > -1;
            if (isWinXP)
                return "WinXP";
            var isWin2003 = sUserAgent.indexOf("Windows NT 5.2") > -1 ||
                sUserAgent.indexOf("Windows 2003") > -1;
            if (isWin2003)
                return "Win2003";
            var isWinVista = sUserAgent.indexOf("Windows NT 6.0") > -1 ||
                sUserAgent.indexOf("Windows Vista") > -1;
            if (isWinVista)
                return "WinVista";
            var isWin7 = sUserAgent.indexOf("Windows NT 6.1") > -1 ||
                sUserAgent.indexOf("Windows 7") > -1;
            if (isWin7)
                return "Win7";
            var isWin10 = sUserAgent.indexOf("Windows NT 10") > -1 ||
                sUserAgent.indexOf("Windows 10") > -1;
            if (isWin10)
                return "Win10";
        }
        return "Other";
    },

    //屏幕分辨率
    getResolution: function() {
        return window.screen.width + 'x' + window.screen.height;
    },

    //获取随机数
    getRandomString: function(len) {
        len = len || 10;
        var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
        var maxPos = $chars.length;
        var pwd = '';
        for (i = 0; i < len; i++) {
            pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    },
    //获取当前时间戳
    getCurrentTs: function() {
        var date = YYTUbaLogUtils.getCurrentDate();
        var time = new Date();
        var hours = time.getHours().toString(); // 时
        if (hours.length == 1)
            hours = '0' + hours;
        var min = time.getMinutes().toString(); // 分
        if (min.length == 1)
            min = '0' + min;
        var second = time.getSeconds().toString(); // 秒
        if (second.length == 1)
            second = '0' + second;
        return date + ' ' + hours + ':' + min + ':' + second;
    },
    //获取当前年
    getCurrentYear: function() {
        var date = new Date();
        var year = date.getFullYear().toString(); // 年;
        return year;
    },

    //获取当前月
    getCurrentMonth: function() {
        var date = new Date();
        var month = parseInt(date.getMonth().toString()) + 1; // 月
        if (month.toString().length == 1)
            month = '0' + month;
        return '' + month;
    },

    //获取档期你日期  yyyy-MM-dd
    getCurrentDate: function() {
        var date = new Date();
        var year = date.getFullYear().toString(); // 年;
        var month = parseInt(date.getMonth().toString()) + 1; // 月
        if (month.toString().length == 1)
            month = '0' + month;
        var day = date.getDate().toString(); // 日
        if (day.length == 1)
            day = '0' + day;
        return year + '-' + month + '-' + day;
    },
    ajaxObject: function() {
        var xmlHttp;
        try {
            // Firefox, Opera 8.0+, Safari
            xmlHttp = new XMLHttpRequest();
        } catch (e) {
            // Internet Explorer
            try {
                xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    return false;
                }
            }
        }
        return xmlHttp;
    },
    //ajax 请求
    ajaxPost: function(url, data, fnSucceed, fnFail, fnLoading) {
        var ajax = YYTUbaLogUtils.ajaxObject();
        ajax.open("post", url, true);
        ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        ajax.onreadystatechange = function() {
            if (ajax.readyState == 4) {
                if (ajax.status == 200) {
                    if (typeof(fnSucceed) == 'function')
                        fnSucceed(ajax.responseText);
                } else {
                    if (typeof(fnFail) == 'function')
                        fnFail("HTTP请求错误！错误码：" + ajax.status);
                }
            } else {
                if (typeof(fnLoading) == 'function')
                    fnLoading();
            }
        }
        ajax.send(data);

    },
    //ajax 请求
    ajaxGet: function(url, data, fnSucceed, fnFail, fnLoading) {
        var ajax = YYTUbaLogUtils.ajaxObject();
        ajax.open("get", url, true);
        ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        ajax.onreadystatechange = function() {
            if (ajax.readyState == 4) {
                if (ajax.status == 200) {
                    if (typeof(fnSucceed) == 'function')
                        fnSucceed(ajax.responseText);
                } else {
                    if (typeof(fnFail) == 'function')
                        fnFail("HTTP请求错误！错误码：" + ajax.status);
                }
            } else {
                if (typeof(fnLoading) == 'function')
                    fnLoading();
            }
        }
        try {
            ajax.send(data);
        } catch (e) {

        }


    }
};